import shutil
import glob
import os
import openpyxl
import zhconv

problem_files_folder = r"C:\Users\yang.lei\Downloads\prblems"
os.makedirs(problem_files_folder, exist_ok=True)


def read_file(file):
    with open(file, 'r', encoding='utf8', errors='ignore') as f:
        return f.read()


def write_file(content, file):
    with open(file, "w", encoding='utf-8') as fw:
        fw.write(content)


def traditional_to_simplified(data_file, output_file, is_excel):
    try:
        with open(data_file, "r") as file:
            file.close()
    except IOError:
        print(f"{data_file} 正被占用无法操作，跳过")
        return
    try:
        if is_excel:
            wb = openpyxl.load_workbook(data_file)
            ws = wb.active
            for row in ws.iter_rows(min_row=1,
                                    max_row=ws.max_row,
                                    min_col=1,
                                    max_col=ws.max_column):
                for cell in row:
                    if isinstance(cell.value, str):
                        zh = zhconv.convert(cell.value, 'zh-cn')
                        cell.value = zh
            wb.save(output_file)
            print(f"{data_file} --> {output_file}")
        else:
            content = read_file(data_file)
            zh = zhconv.convert(content, 'zh-cn')
            write_file(zh, output_file)
            print(f"{data_file} --> {output_file}")
    except Exception as e:
        # 遇到问题文件，则输出文件名和错误原因，复制文件到指定文件夹以便调查，继续处理其他文件
        print(data_file, e)
        shutil.copy2(data_file, problem_files_folder)


def process_files_in_folder(input_folder, output_folder):
    for data_file in glob.glob(rf'{input_folder}\**\*.*', recursive=True):
        _, ext = os.path.splitext(data_file)
        ext = ext.lower()
        if not ext in {'.xlsx', '.csv'}:
            continue
        output_file = data_file.replace(input_folder, output_folder)
        os.makedirs(os.path.dirname(output_file), exist_ok=True)
        traditional_to_simplified(data_file, output_file, is_excel=ext == '.xlsx')


if __name__ == '__main__':
    process_files_in_folder(
        # r"D:\dl\input",r"D:\dl\output",
        r"C:\Users\yang.lei\Downloads\input", r"C:\Users\yang.lei\Downloads\output",
    )
